package com.mitac.mcd.mobiletracking.managementclient.impl;

import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mitac.mcd.mobiletracking.managementclient.ISocketServer;
import com.mitac.mcd.mobiletracking.servlets.initParameters;

public class JSocketServerImpl implements ISocketServer{

	public static String server = initParameters.ConfigProperties.get("SOCKET_SERVER").toString();
	
	public  JSocketServerImpl() {
		
	}
	
	@Override
	public String getAfterCloseSocketDoneAverageTime() {
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	ResultSet rs = null;
    	int avg_time = 0;
    	String [] servers = null;
		if (server.indexOf(",")>=0) {
			servers = server.split(",");
		}else{
			servers = new String[]{server};
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		sb.append("<servers>");
		try {
			dbc = DBConnection.getConnection();
			for(String s:servers){
				String sqlA = " select avg(DIFF_TIME) as avg_time from CLOSESOCKET_LOG " +
				" where IPADDRESS = '"+s+"' " ;
				System.out.println("getAfterCloseSocketDoneAverageTime:"+sqlA);
				pst = dbc.prepareStatement(sqlA);
				rs = pst.executeQuery();
				while(rs.next()){
					avg_time = rs.getInt("avg_time");
				}
				sb.append("<server>");
				sb.append("<ip>").append(s).append("</ip>");
				sb.append("<avg_time>").append(avg_time).append("</avg_time>");
				sb.append("</server>");
			}
			if(null!=rs) rs.close();
            dbc.close();
            pst.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
        
		sb.append("</servers>");
		return sb.toString();
	}
	
	@Override
	public String getServerConfiguration() {
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		sb.append("<servers>");
		String [] servers = null;
		if (server.indexOf(",")>=0) {
			servers = server.split(",");
		}else{
			servers = new String[]{server};
		}
		for(String s:servers){
			String[] temp = s.split(":");
			String ip = temp[0];
			int port = Integer.parseInt(temp[1]);
			System.out.println("ip:"+ip+",port:"+port);
			try {
				Socket socket = new Socket();
				SocketAddress socketaddress = new InetSocketAddress(ip,port);
				socket.connect(socketaddress,5*1000);
				OutputStream Os = null;
				PrintStream PS = null;
				BufferedReader IS = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
				if (!socket.isClosed()){
	                Os = socket.getOutputStream();
	                PS = new PrintStream(Os);
	    		}
				String command = "{\"cmd\":\"serverconfig\"}";
	    		PS.println(command);
	    		socket.setSoTimeout(10*1000);
	    		String str = null;
	    		while(true){
	    			try{
	    				str = IS.readLine();
	    				break;
	    			}catch(SocketTimeoutException e){
	    				break;
	    			}
	    		}
	    		System.out.println("Server said:"+str);
	    		if(str!=null&&!str.equals("")){
	    			sb.append(str);
	    		}
	    		socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		sb.append("</servers>");
		return sb.toString();
	}
	
	
	public String getServerCurrentStatus() {
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		sb.append("<servers>");
		String [] servers = null;
		if (server.indexOf(",")>=0) {
			servers = server.split(",");
		}else{
			servers = new String[]{server};
		}
		for(String s:servers){
			String[] temp = s.split(":");
			String ip = temp[0];
			int port = Integer.parseInt(temp[1]);
			System.out.println("ip:"+ip+",port:"+port);
			try {
				Socket socket = new Socket();
				SocketAddress socketaddress = new InetSocketAddress(ip,port);
				socket.connect(socketaddress,5*1000);
				OutputStream Os = null;
				PrintStream PS = null;
				BufferedReader IS = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
				if (!socket.isClosed()){
	                Os = socket.getOutputStream();
	                PS = new PrintStream(Os);
	    		}
				String command = "{\"cmd\":\"serverstatus\"}";
	    		PS.println(command);
	    		socket.setSoTimeout(10*1000);
	    		String str = null;
	    		while(true){
	    			try{
	    				str = IS.readLine();
	    				break;
	    			}catch(SocketTimeoutException e){
	    				break;
	    			}
	    		}
	    		System.out.println("Server said:"+str);
	    		if(str!=null&&!str.equals("")){
	    			sb.append(str);
	    		}
	    		socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		sb.append("</servers>");
		return sb.toString();
	}

	public String getExceptionStatisticPeriod(String startDay, String endDay,String id,String type) {
		StringBuffer exception_statistic = new StringBuffer("");
		exception_statistic.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		exception_statistic.append("<exception_statistic>");
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	ResultSet rs = null;
    	String sqlA = " select el.EXCEPTION_PROP_CODE,ep.NOTE,count(el.EXCEPTION_PROP_CODE) as error_count " +
    			" from exception_log el,EXCEPTIONPROPERTIES ep" +
    			" where el.EXCEPTION_PROP_CODE = ep.EXCEPTION_PROP_CODE and " +
    			" el.RECORD_TIME between '"+startDay+"' and DATE_ADD('"+endDay+"',INTERVAL 1 DAY) ";
    	if (id!=null&&!id.equals("")){
    		if (type.equalsIgnoreCase("uuid")){
    			sqlA = sqlA + " and el.UUID = '"+id+"' ";
    		}
    		if (type.equalsIgnoreCase("userid")){
    			sqlA = sqlA + " and el.USER_ID = "+id;
    		}
    	}
    	sqlA = sqlA + " group by el.EXCEPTION_PROP_CODE";
    	System.out.println("执行sql:"+sqlA);
        try {
            dbc = DBConnection.getConnection();
			pst = dbc.prepareStatement(sqlA);
			rs = pst.executeQuery();
			while(rs.next()){
				exception_statistic.append("<exception>");
				exception_statistic.append("<error_code>").append(rs.getString("EXCEPTION_PROP_CODE")).append("</error_code>");
				exception_statistic.append("<note>").append(rs.getString("NOTE")).append("</note>");
				exception_statistic.append("<count>").append(rs.getInt("error_count")).append("</count>");
				exception_statistic.append("</exception>");
			}
			
			if(null!=rs) rs.close();
			dbc.close();
            pst.close();
		} catch (Exception e) {
			System.out.println("getExceptionStatisticPeriod:"+e);
		}
		exception_statistic.append("</exception_statistic>");
		return exception_statistic.toString();
	}
	
	public String getNotificationClientCountPeriod(String startDay,
			String endDay) {
		StringBuffer notification_statistic = new StringBuffer("");
		notification_statistic.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		notification_statistic.append("<notification_statistic>");
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	ResultSet rs = null;
    	String sqlA = " select "+
    					" sum(case when nd.FAIL_CODE is null then 1 end) success_count,"+
						" sum(case when nd.FAIL_CODE is null and nd.RESEND_TIME <> 0 then 1 end) success_resend_count,"+
						" sum(case when nd.FAIL_CODE is not null then 1 end) fail_count,"+
						" sum(case when nd.FAIL_CODE is not null and nd.RESEND_TIME <> -1 then 1 end) fail_resend_count "+
						" from NOTIFICATION_DETAIL nd,notification_log n "+
						" where n.IS_VALIDATE = 1 and "+
						" nd.NOTIFICATION_ID = n.NOTIFICATION_ID and "+
						" LOG_TIME between '"+startDay+"' and DATE_ADD('"+endDay+"',INTERVAL 1 DAY) ";
    	System.out.println("执行sql:"+sqlA);
        try {
            dbc = DBConnection.getConnection();
			pst = dbc.prepareStatement(sqlA);
			rs = pst.executeQuery();
			while(rs.next()){
				notification_statistic.append("<success_count>").append(rs.getInt("success_count")).append("</success_count>");
				notification_statistic.append("<success_resend_count>").append(rs.getInt("success_resend_count")).append("</success_resend_count>");
				notification_statistic.append("<fail_count>").append(rs.getInt("fail_count")).append("</fail_count>");
				notification_statistic.append("<fail_resend_count>").append(rs.getInt("fail_resend_count")).append("</fail_resend_count>");
			}
			
			if(null!=rs) rs.close();
			dbc.close();
            pst.close();
		} catch (Exception e) {
			System.out.println("getNotificationCountPeriod:"+e);
		}
		notification_statistic.append("</notification_statistic>");
		return notification_statistic.toString();
	}
	
	public String getNotificationCountPeriod(String startDay, String endDay) {
		StringBuffer notification_statistic = new StringBuffer("");
		notification_statistic.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		notification_statistic.append("<notification_statistic>");
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	ResultSet rs = null;
    	String sqlA = " select "+
    					" count(ID) notification_count,sum(CLIENT_COUNT) client_count,"+
						" case when type = 1 and NEWEST = 1 then count(ID) end newest_order_notification_count,"+
						" case when type = 1 and NEWEST = 1 then sum(CLIENT_COUNT) end newest_order_client_count,"+
						" case when type = 0 and NEWEST = 1 then count(ID) end newest_msg_notification_count,"+
						" case when type = 0 and NEWEST = 1 then sum(CLIENT_COUNT) end newest_msg_client_count,"+
						" case when type = 1 and NEWEST = 0 then count(ID) end unread_order_notification_count,"+
						" case when type = 1 and NEWEST = 0 then sum(CLIENT_COUNT) end unread_order_client_count,"+
						" case when type = 0 and NEWEST = 0 then count(ID) end unread_msg_notification_count,"+
						" case when type = 0 and NEWEST = 0 then sum(CLIENT_COUNT) end unread_msg_client_count"+
						" from notification_log"+
						" where IS_VALIDATE = 1 and"+
						" LOG_TIME between '"+startDay+"' and DATE_ADD('"+endDay+"',INTERVAL 1 DAY) ";
    	System.out.println("执行sql:"+sqlA);
        try {
            dbc = DBConnection.getConnection();
			pst = dbc.prepareStatement(sqlA);
			rs = pst.executeQuery();
			while(rs.next()){
				notification_statistic.append("<cmd_count>").append(rs.getInt("notification_count")).append("</cmd_count>");
				notification_statistic.append("<cmd_client_count>").append(rs.getInt("client_count")).append("</cmd_client_count>");
				notification_statistic.append("<newest_order_notification_count>").append(rs.getInt("newest_order_notification_count")).append("</newest_order_notification_count>");
				notification_statistic.append("<newest_order_client_count>").append(rs.getInt("newest_order_client_count")).append("</newest_order_client_count>");
				notification_statistic.append("<newest_msg_notification_count>").append(rs.getInt("newest_msg_notification_count")).append("</newest_msg_notification_count>");
				notification_statistic.append("<newest_msg_client_count>").append(rs.getInt("newest_msg_client_count")).append("</newest_msg_client_count>");
				notification_statistic.append("<unread_order_notification_count>").append(rs.getInt("unread_order_notification_count")).append("</unread_order_notification_count>");
				notification_statistic.append("<unread_order_client_count>").append(rs.getInt("unread_order_client_count")).append("</unread_order_client_count>");
				notification_statistic.append("<unread_msg_notification_count>").append(rs.getInt("unread_msg_notification_count")).append("</unread_msg_notification_count>");
				notification_statistic.append("<unread_msg_client_count>").append(rs.getInt("unread_msg_client_count")).append("</unread_msg_client_count>");
			}
			
			if(null!=rs) rs.close();
			dbc.close();
            pst.close();
		} catch (Exception e) {
			System.out.println("getNotificationCountPeriod:"+e);
		}
		notification_statistic.append("</notification_statistic>");
		return notification_statistic.toString();
	}
	
	public static void main(String args[]){
		String sserver = "127.0.0.1:9000,128.0.0.1:8080";
		String [] servers = null;
		if (sserver.indexOf(",")>=0) {
			servers = sserver.split(",");
		}else{
			servers = new String[]{sserver};
		}
		StringBuffer strServers = new StringBuffer();
		for(String s:servers){
			strServers.append("'").append(s).append("'").append(",");
		}
		System.out.println(strServers.substring(0,strServers.length()-1).toString());
	}
}
